import { Graph, View } from '@antv/x6';
import { createApp, reactive, defineComponent, onMounted, onUnmounted, PropType, ref, watch,inject } from 'vue';
import { getMindmapData, getIndexCells,findItem, replaceNode, replaceAllNode} from './detailEdge';
import { TeleportContainer } from './registerDetailIndex';
import DetailEdgeLabel from './detailEdgeLabel';
import {nanoid} from  'nanoid'
import Bus from '@/utils/emmit'
import {cloneDeep} from 'lodash'
import API from '@/services';
import { useRouter, useRoute} from 'vue-router';
import { Message } from '@arco-design/web-vue';
import {getYearWeek, getQuerterFormatter} from '@/utils/util';
export default defineComponent({
    name: 'IndexGraph',
    props: {
        treedata: {
            type: Object as PropType<any>
        },
        // 用于全局过滤
        getIndexTreeCard: {
            type: Array as PropType<Array<any>>,
            default: []
        },
        // 用于单个指标卡过滤
        singleFilterTreeData: {
            type: Array as PropType<Array<any>>,
            default: []
        },
        initCardData: {
            type: Array as PropType<Array<any>>,
            default: []
        }
    },
    // inject: ["getGraph", "getNode"],
    setup: (props, {emit}) => {
        const domRef = ref();
         // todo: 是否需要 ref
        const graphContext = ref();
        const getParentId = ref()
        const router = useRouter();
        const route = useRoute();
        const getPreviewData = ref<any>()
        const id = route.query.id
        const getSelfNode = ref<any>()
        const initGraph = () => {
            if (domRef.value) {
                graphContext.value = new Graph({
                container: domRef.value,
                // autoResize: true,
                autoResize: document.body,
                connecting: {
                    connectionPoint: 'anchor',
                },
                grid: {
                    size: 10,
                    visible: true,
                    type: 'dot', // 'dot' | 'fixedDot' | 'mesh'
                    args: {
                    color: '#D4D7E1', // 网格线/点颜色
                    thickness: 1, // 网格线宽度/网格点大小
                    },
                },
                interacting: {
                    nodeMovable: false,
                },
                panning: {
                    enabled: true,
                    eventTypes: ['leftMouseDown', 'mouseWheel'],
                },
                mousewheel: {
                    enabled: true,
                    modifiers: 'ctrl',
                    factor: 1.1,
                    maxScale: 1.5,
                    minScale: 0.5,
                },
                onEdgeLabelRendered: (args:any) => {
                    const { selectors, edge: { data: { source,target } } } = args
                    const content = selectors.foContent as HTMLDivElement
                    if (content) {
                        // @ts-ignore
                      const app = createApp(<DetailEdgeLabel data={source}/>);
                      app.mount(content)

                    }
                },
                })
                graphContext.value.on('node:mouseenter', ({ node }: any) => {
                    getParentId.value = node?.id
                })
            }
        }
        onUnmounted(() => {
            graphContext.value.dispose()
        })
        onMounted(()=>{
            initGraph()
        })
        const onPopPicker = (v:any) => {
            if (v) {
                graphContext.value.disablePanning()
            } else {
                graphContext.value.enablePanning()
            }
        }
        Bus.on('onDetailRestEvent', () => {
            graphContext.value.centerContent()
        })
        const onSingleCardFilter = (data: any, v:any) => {
            const findCurentIndex = props.singleFilterTreeData.find((item:any) =>item.keys === v.id)
            findCurentIndex.gapValue = ''
            findCurentIndex.value = ''
            findCurentIndex.dateCondition.fixDate = data
            delete findCurentIndex.sqlFormat
            delete findCurentIndex.dateTime

            const previewDataClone = cloneDeep(findCurentIndex)
            const dateCondition = previewDataClone.dateCondition
            // 默认数据时间的配置
            if ( dateCondition.dateMode === 'FIXDATE') {
                if (dateCondition.timeUnit === 'WEEK') {
                    
                    dateCondition.fixDate = getYearWeek(new Date(dateCondition.fixDate))
                }
                if (dateCondition.timeUnit === 'QUARTER') {
                    dateCondition.fixDate = getQuerterFormatter(dateCondition.fixDate)
                }
            }
            previewDataClone.dateCondition.dateMode = 'FIXDATE'
            previewApi(previewDataClone, v.id, findCurentIndex)
        }
        // 全局过滤
        const onGlobalFilter = async (data:any) => {
            const replaceNode = replaceAllNode(props.treedata, data)
            console.log(props.treedata)
            replaceNode.rootTreeCard = true
            if (replaceNode) {
                const models = getIndexCells(props.treedata, onSingleCardFilter, onGlobalFilter,onPopPicker);
                graphContext.value.fromJSON(models)
            }
        }
         // 调用预览的接口
        const previewApi = async (card:any, id:any, findCurentIndex?:any) => {
            try {
                const {code, data} = await API.metricsTree.postCardPreview(card)
                if (code === 200) {
                    getPreviewData.value = data
                    getPreviewData.value.id = getPreviewData.value.keys
                    getPreviewData.value.dateCondition.fixDate = findCurentIndex.dateCondition.fixDate
                    const resultNode = replaceNode(props.treedata, getPreviewData.value, id)
                    if (resultNode) {
                        const models = getIndexCells(props.treedata, onSingleCardFilter, onGlobalFilter,onPopPicker);
                        graphContext.value.fromJSON(models)
                    }
                    Message.success('预览成功')
                }
            } catch (error) {

            }
        }
        watch(() => props.treedata, () => {
            if (props.treedata) {
                const replaceNode = replaceAllNode(props.treedata, props.initCardData)
                replaceNode.rootTreeCard = true
                if (replaceNode) {
                    const models = getIndexCells(props.treedata, onSingleCardFilter, onGlobalFilter,onPopPicker );
                    graphContext.value.fromJSON(models)
                    setTimeout(() => {
                        graphContext.value.positionPoint({ x: models?.nodes?.[0]?.x, y: models?.nodes?.[0]?.y }, 10, '42%')
                    }, 100)
                }
            }
        })
        watch(
            ()=> props.getIndexTreeCard,
            (val)=>{
                if (val?.length) {
                    val.forEach(item=>{
                        item.dateCondition.fixDate = item.dateTime
                    })
                    onGlobalFilter(val)
                }
            },
            {
                immediate: true
            }
        )
        return () => {
            return (
                <>
                    <TeleportContainer />
                    <div ref={domRef}  style={{ width: '100%', height: '100%',background: '#fff' }}></div>
                </>
            )
        }
    }
})
